package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Carousel;
import io.wins.vertx.service.CarouselService;

public class CarouselApiVerticle extends RestApiVerticle {

    public static final String REST_ADDRESS = "io.wins.rest.carousel#%1$s";
    private static final Logger logger = LoggerFactory.getLogger(CarouselApiVerticle.class);

    public final CarouselService service;

    public CarouselApiVerticle(final CarouselService carouselService) {
        this.service = carouselService;
    }

    @Override
    public void start(final Future<Void> startFuture) throws Exception {
        super.start();
        this.on(String.format(REST_ADDRESS, CREATE), this::createCarousel);
        this.on(String.format(REST_ADDRESS, LIST), this::listCarousel);
        this.on(String.format(REST_ADDRESS, UPDATE), this::updateCarousel);
        this.on(String.format(REST_ADDRESS, DELETE), this::deleteCarousel);
        startFuture.complete();
    }

    private void deleteCarousel(final Message<JsonObject> tMessage) {
        final String id = tMessage.body().getJsonObject("param").getString("id");
        this.service.deleteCarousel(id, tMessage);
    }

    private void updateCarousel(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("carData");
        final Carousel carousel = new Carousel(body);
        this.service.updateCarousel(carousel, tMessage);
    }

    private void listCarousel(final Message<JsonObject> tMessage) {
        this.service.listCarousel(tMessage);
    }

    private void createCarousel(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("carData");
        final Carousel carousel = new Carousel(body);
        System.out.println(carousel.toJson());
        this.service.createCarousel(carousel, tMessage);
    }
}
